"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
from utime import sleep_ms
from microWebSrv import MicroWebSrv
from config import Config
from utils import wol, acs, log
from aligenie.aligenie import Aligenie


web_server = None

"""
WebRoute
"""
@MicroWebSrv.route('/', 'GET')
def homepage(httpClient, httpResponse):
	httpResponse.WriteResponseOk(
		headers = None,
        contentType = "text/html",
        contentCharset = "UTF-8",
        content = '<h1>Aligenie Service Running...</h1>')

@MicroWebSrv.route('{}'.format(Config.SERVER_SKILL_ROUTE), 'POST')
def skill(httpClient, httpResponse):
	# print(httpClient.ReadRequestContentAsJSON())
	aligenie = Aligenie(httpClient.ReadRequestContentAsJSON())
	log.logger("[device]: {}, [skill]: {}, [intent]: {}, [ut]: {}".format(aligenie.device_id, aligenie.skill_name, aligenie.intent_name, aligenie.utterance))

	ACTION_WOL = False
	ACTION_ACS = False

	if aligenie.skill_name == Config.SKILL_NAME:
		if aligenie.intent_name == Config.INTENT_WEATHER:
			aligenie.reply = "查询内容：天气；查询城市：{} ；查询日期：{}".format(aligenie.city, aligenie.date)
		elif aligenie.intent_name == Config.INTENT_WOL:
			ACTION_WOL = True
			aligenie.reply = "正在开启这台{}".format(aligenie.computer)
			
			if Config.IS_MULTI_DEVICES:
				if aligenie.device_id not in Config.VALID_DEVICE_IDS:
					ACTION_WOL = False
					aligenie.reply = "抱歉，我无权开启这台{}".format(aligenie.computer)
		elif aligenie.intent_name == Config.INTENT_ENVIRONMENT:
			pass
		elif aligenie.intent_name == Config.INTENT_CONTROL:
			pass
		elif aligenie.intent_name == Config.INTENT_ACS:
			ACTION_ACS = True
			aligenie.reply = "已下发指令"
	else:
		aligenie.reply = "技能不存在，或暂时无法查询！"

	httpResponse.WriteResponseJSONOk(aligenie.response)

	if ACTION_WOL:
		wol.wake_on_lan(Config.WOL_MAC_LISTS[aligenie.computer])
	elif ACTION_ACS:
		acs.open_the_door()




def start_web_server():
	global web_server

	web_server = MicroWebSrv(webPath=Config.SERVER_ROOT, port=Config.SERVER_PORT)
	web_server.SetNotFoundPageUrl('/')
	web_server.Start(threaded=True)
	
	log.logger("Web Server Started")


if __name__ == "__main__":
	try:
		start_web_server()
	except KeyboardInterrupt:
		print("\nPRESS CTRL+D TO RESET DEVICE")

		if web_server is not None:
			web_server.Stop()
